package y2015.date1016am.http编程_下载;

import org.junit.jupiter.api.Test;

import java.io.*;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;

public class HttpVisit {
    static String httpAddress;

    @Test
    public void main() throws Exception {
        String fileDirOfDownload = "sample/2016";
//		String fileNameOfDownload = "2088637.html";
//		String localHostIp = InetAddress.getLocalHost().getHostAddress();
//		httpAddress = "http://www.cnblogs.com/over140/archive/2011/06/24/"+fileNameOfDownload;
        httpAddress = "http://ttl4.pc6.com/wgd/yunxian.zip";
        String fileNameOfDownload = "yunxian.zip";
        Download(httpAddress, fileDirOfDownload, fileNameOfDownload);
    }

    /**
     * 从网页下载文件
     * <p>
     *
     * @param httpAddress        <p>要下载的文件的网络地址
     * @param fileDirOfDownload  <p>要保存的文件的目录
     * @param fileNameOfDownload <p>要下载的文件名
     * @throws IOException
     */
    private static void Download(String httpAddress, String fileDirOfDownload, String fileNameOfDownload) {
        File file = new File(fileDirOfDownload, fileNameOfDownload);
        BufferedInputStream in = null;
        BufferedOutputStream out = null;

        try {
            URL url = new URL(httpAddress);
            URLConnection conn = url.openConnection();
            in = new BufferedInputStream(conn.getInputStream());
            out = new BufferedOutputStream(new FileOutputStream(file));
            int b, sum = 0;
            byte buffer[] = new byte[8 * 1024];
            while ((b = in.read(buffer)) != -1) {
                out.write(buffer, 0, b);
                System.out.println((sum += b) / 1024 + "kb");

            }
        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                in.close();
                out.flush();
                out.close();
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
        System.out.println("Download finish");
    }
}


